package com.arrogames.blondbattle.game.rendering 
{
	import ash.core.Engine;
	import ash.core.NodeList;
	import ash.core.System;
	import com.arrogames.blondbattle.game.movement.Motion;
	import com.arrogames.blondbattle.input.KeyPoll;
	import com.arrogames.blondbattle.input.TouchPoll;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	import flash.ui.Keyboard;
	import org.as3commons.logging.api.getLogger;
	import org.as3commons.logging.api.ILogger;
	
	/**
	 * ...
	 * @author Robin van den Bogaard
	 */
	public class CameraControlSystem extends System {
		
		private static const logger:ILogger = getLogger(CameraControlSystem);
		
		private var keypoll:KeyPoll;
		private var touchpoll:TouchPoll
		private var worldViewPort:Rectangle;
		private var cams:NodeList;
		private var camera:CameraNode;
		
		public function CameraControlSystem(
										keypoll:KeyPoll, 
										touchpoll:TouchPoll, 
										worldViewPort:Rectangle) {
			super();
			this.keypoll = keypoll;
			this.touchpoll = touchpoll;
			this.worldViewPort = worldViewPort;
			logger.debug("Instantiated");
			
		}
		
		override public function addToEngine( engine : Engine ) : void {
			cams = engine.getNodeList(CameraNode);
			if (cams.head == null) {
				cams.nodeAdded.add(cameraAdded);
			} else {
				camera = cams.head;
			}
		}
		
		private function cameraAdded(node:CameraNode):void {
			cams.nodeAdded.remove(cameraAdded);
			camera = node;
		}
		
		override public function update( time : Number ) : void {
			var maxSpeed:Number = 1200;
			var dampenSpeed:Number = 30;
			var speedIncrement:Number = 40;
			
			var position:Point = camera.position.position;
			var motion:Motion = camera.motion;
			
			var transformX:Number = touchpoll.transformX;
			
			if (transformX > 0) {
				motion.velocity.x = Math.min(motion.velocity.x - (-transformX * speedIncrement), -maxSpeed);
			} else if (transformX <  0) {
				motion.velocity.x = Math.min(motion.velocity.x + (-transformX * speedIncrement), maxSpeed);
			} else if (keypoll.isDown(Keyboard.RIGHT)) {
				motion.velocity.x = Math.min(motion.velocity.x+speedIncrement, maxSpeed);
			} else if (keypoll.isDown(Keyboard.LEFT)) {
				motion.velocity.x = Math.max(motion.velocity.x-speedIncrement, -maxSpeed);
			} else {
				if (motion.velocity.x > 0) {
					motion.velocity.x -= dampenSpeed;
					if (motion.velocity.x < 0) {
						motion.velocity.x = 0;
					}
				} else if (motion.velocity.x < 0) {
					motion.velocity.x += dampenSpeed;
					if (motion.velocity.x > 0) {
						motion.velocity.x = 0;
					}
				}
				
			}
			
			if (position.x < worldViewPort.x) {
				motion.velocity.x = 0;
			}
			if (position.x+camera.lens.viewport.width > worldViewPort.width) {
				motion.velocity.x = 0;
			}
		}

		override public function removeFromEngine( engine : Engine ) : void
		{
			cams = null;
			camera = null;
		}
		
	}

}